// SuperskillController.m
//  This file is part of D&D Manager
//
//  Created by Matthew Hutton on 27/06/2007.
//
//D&D Manager, a D&D Character and battle management program.
//Copyright (C) 2007, Matthew Hutton
//
//This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License along with this program; if not, write to:
//The Free Software Foundation, Inc.,
//51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#import "SuperskillController.h"
#import "AbilityChanged.h"

@implementation SuperskillController
#pragma mark Init
#pragma mark 
-(id)init{
	[super init];
	[NSBundle loadNibNamed:@"Superskill"
					 owner:self];
	[characterClassController setAutomaticallyPreparesContent:NO];
	[characterClassController prepareContent];
	[characterClassController setAutomaticallyPreparesContent:YES];
	[characterClassController setSortDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]]];
	[superskillController setSortDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]]];
	return self;
}
#pragma mark -
#pragma mark Alphabetical
#pragma mark 
-(IBAction)abilityTypeChanged:(id)sender{
	if([[superskillController selectedObjects] count]==0){
		return;
	}
	NSManagedObject *superskill=[[superskillController selectedObjects] objectAtIndex:0];
	NSArray *skills=[[superskill valueForKey:@"skill"] allObjects];
	int i;
	for(i=0;i<[skills count];i++){
		NSManagedObject *skill=[skills objectAtIndex:i];
		[AbilityChanged setupSkillAbilityBonusForSkill:skill
										  forCharacter:[skill valueForKey:@"character"]];
	}
}
-(IBAction)addSuperskill:(id)sender{
	NSManagedObject *superskill=[superskillController newObject];
	[self processSkillIsClassSkill];
	[characterClassTable reloadData];
	[superskillController addObject:superskill];
}
-(IBAction)armourClassCheckChanged:(id)sender{
	if([[superskillController selectedObjects] count]==0){
		return;
	}
	BOOL state=[sender state];
	NSManagedObject *superskill=[[superskillController selectedObjects] objectAtIndex:0];
	NSArray *skills=[[superskill valueForKey:@"skill"] allObjects];
	int i;
	for(i=0;i<[skills count];i++){
		[[skills objectAtIndex:i] setValue:[NSNumber numberWithBool:state]
									forKey:@"armourCheckPressed"];
	}
}
- (IBAction)characterClassTableChanged:(id)sender
{
	if([[superskillController selectedObjects] count]==0){
		return;
	}
	//NSLog(@"Hello, table has been activated.");
	//NSLog(@"selected row=%d",[characterClassTable selectedRow]);
	int row=[characterClassTable selectedRow];
	NSManagedObject *characterClass=[[characterClassController arrangedObjects] objectAtIndex:row];
	NSManagedObject *superskill=[[superskillController selectedObjects] objectAtIndex:0];
	NSSet *ccsNonMut=[superskill valueForKey:@"classSkillFor"];
	NSMutableSet *characterClasses=[NSMutableSet setWithCapacity:[ccsNonMut count]];
	[characterClasses setSet:ccsNonMut];
	if([[skillIsClassSkill objectAtIndex:row] boolValue]){
		//removing.
		[characterClasses removeObject:characterClass];
		[skillIsClassSkill replaceObjectAtIndex:row withObject:[NSNumber numberWithBool:NO]];
	}else{
		[characterClasses addObject:characterClass];
		[skillIsClassSkill replaceObjectAtIndex:row withObject:[NSNumber numberWithBool:YES]];
	}
	[superskill setValue:characterClasses
				  forKey:@"classSkillFor"];
	[characterClassTable reloadData];
	//NSLog(@"table activation finished");
	//now process subskills
	int i;
	NSArray *skillsToChange=[[[superskill valueForKey:@"skill"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"character.characterClass1.name like[c] \"%@\" OR character.characterClass2.name like[c] \"%@\" OR character.characterClass3.name like[c] \"%@\"",[characterClass valueForKey:@"name"],[characterClass valueForKey:@"name"],[characterClass valueForKey:@"name"]]]];
	NSManagedObject *obj;
	for(i=0;i<[skillsToChange count];i++){
		NSManagedObject *skill=[skillsToChange objectAtIndex:i];
		if(i==0){
			obj=[skill valueForKey:@"character"];
		}
		BOOL aClassExists=NO;
		BOOL classSkill=NO;
		int j;
		for(j=1;j<4;j++){
			NSManagedObject *cc=[obj valueForKey:[NSString stringWithFormat:@"characterClass%d",j]];
			if(cc!=nil){
				aClassExists=YES;
				if([characterClasses containsObject:cc]){
					classSkill=YES;
				}
			}
		}		
		if(aClassExists){
			if(classSkill){
				[skill setValue:[NSNumber numberWithBool:NO]
						 forKey:@"crossClass"];
			}else{
				[skill setValue:[NSNumber numberWithBool:YES]
						 forKey:@"crossClass"];
			}
		}else{
			[skill setValue:[NSNumber numberWithBool:NO]
					 forKey:@"crossClass"];
		}
	}
}

- (IBAction)closeWindow:(id)sender
{

	//NSLog(@"context found");
	//NSManagedObjectModel *model=[[mObjC persistentStoreCoordinator] managedObjectModel];
	[superskillWindow orderOut:sender];
	[NSApp endSheet:superskillWindow];
}
-(void)controlTextDidEndEditing:(NSNotification *)aNotification{
	if([[aNotification object] isEqualTo:nameTF] || [[aNotification object] isEqualTo:superskillTable]){
		//check name is different from existing.
		NSManagedObject *superskill=[[superskillController selectedObjects] objectAtIndex:0];
		NSString *name=[[aNotification object] stringValue];
		NSArray *array=[[superskillController arrangedObjects] valueForKey:@"name"];
		BOOL nameIncluded=NO;
		int i;
		for(i=0;i<[array count];i++){
			if([[array objectAtIndex:i] isEqualToString:name]){
				nameIncluded=YES;
				break;
			}
		}
		if(nameIncluded){
			BOOL goOn=NO;
			int j=2;
			while(!goOn){
				BOOL nameIncluded2=NO;
				int i;
				for(i=0;i<[array count];i++){
					if([[array objectAtIndex:i] isEqualToString:[NSString stringWithFormat:@"%@ #%d",name,j]]){
						nameIncluded2=YES;
						break;
					}
				}
				if(nameIncluded2){
					j++;
				}else{
					[superskill setValue:[NSString stringWithFormat:@"%@ #%d",name,j] forKey:@"name"];
					goOn=YES;
					break;
				}
			}
		}
	}
}
-(void)displaySuperskillWindowAttachedToWindow:(NSWindow *)windowAttachedTo
								withCharacters:(NSArray *)chars{
	[superskillController setAutomaticallyPreparesContent:NO];
	[superskillController prepareContent];
	[superskillController setAutomaticallyPreparesContent:YES];
	characters=chars;
	if([[superskillController arrangedObjects] count]>0 && [[superskillController selectedObjects] count]==0){
		[superskillController setSelectionIndex:0];
	}
	[self processSkillIsClassSkill];
	[characterClassTable reloadData];
	[NSApp beginSheet:superskillWindow
	   modalForWindow:windowAttachedTo
		modalDelegate:self
	   didEndSelector:nil
		  contextInfo:NULL];
}
-(NSManagedObjectContext *)managedObjectContext{
	return [[[NSDocumentController sharedDocumentController] currentDocument] managedObjectContext];
}
-(void)processSkillIsClassSkill{
	NSArray *characterClasses=[characterClassController arrangedObjects];
	if(skillIsClassSkill==nil){
		skillIsClassSkill=[[NSMutableArray alloc] initWithCapacity:[characterClasses count]];
	}else{
		[skillIsClassSkill removeAllObjects];
	}
	if([[superskillController selectedObjects] count]==0){
		return;
	}
	NSManagedObject *superskill=[[superskillController selectedObjects] objectAtIndex:0];
	int i;
	for(i=0;i<[characterClasses count];i++){
		NSManagedObject *characterClass=[characterClasses objectAtIndex:i];
		if([[superskill valueForKey:@"classSkillFor"] containsObject:characterClass]){
			[skillIsClassSkill addObject:[NSNumber numberWithBool:YES]];
		}else{
			[skillIsClassSkill addObject:[NSNumber numberWithBool:NO]];
		}
	}
}
-(NSWindow *)superskillWindow{
	return superskillWindow;
}
-(void)tableViewSelectionDidChange:(NSNotification *)notification{
	if([[notification object] isEqualTo:superskillTable]){
		if([[superskillController selectedObjects] count]>0){
			[self processSkillIsClassSkill];
			[characterClassTable reloadData];
		}
	}
}
-(IBAction)untrainedPressed:(id)sender{
	if([[superskillController selectedObjects] count]==0){
		NSLog(@"untrained cannot change, no superskill selected");
	}
	NSManagedObject *superskill=[[superskillController selectedObjects] objectAtIndex:0];
	if([sender state]==0){
		//unchecked so removing.
		NSArray *skillsToGo=[[[superskill valueForKey:@"skill"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"rank==0"]];
		int i;
		NSManagedObjectContext *mObjC=[[[NSDocumentController sharedDocumentController] currentDocument] managedObjectContext];
		for(i=0;i<[skillsToGo count];i++){
			[mObjC deleteObject:[skillsToGo objectAtIndex:i]];
		}
	}else{
		//checked so adding.
		//get all characters and add to those without the skill.
		NSArray *charactersWithout=[characters filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"NOT (ANY skills.superskill.name like[c] \"%@\")",[superskill valueForKey:@"name"]]]];
		int i;
		for(i=0;i<[charactersWithout count];i++){
			NSManagedObject *obj=[charactersWithout objectAtIndex:i];
			[AbilityChanged createAndSetupSkillFromSuperskill:superskill
												 forCharacter:obj];
		}
	}
}
#pragma mark -
#pragma mark Table Actions
#pragma mark
-(int)numberOfRowsInTableView:(NSTableView *)aTableView{
	if([aTableView isEqualTo:characterClassTable]){
		return [[characterClassController arrangedObjects] count];
	}
	return 0;
}
-(id)tableView:(NSTableView *)aTableView
objectValueForTableColumn:(NSTableColumn *)aTableColumn
		   row:(int)row{
	if([aTableView isEqualTo:characterClassTable]){
		if([aTableColumn isEqualTo:[[aTableView tableColumns] objectAtIndex:0]]){
			return [skillIsClassSkill objectAtIndex:row];
		}else{
			return [[[characterClassController arrangedObjects] objectAtIndex:row] valueForKey:@"name"];
		}
	}
	return nil;
}
#pragma mark -
#pragma mark Dealloc
#pragma mark 
-(void)dealloc{
	if(skillIsClassSkill!=nil){
		[skillIsClassSkill release];
	}
	[super dealloc];
}
@end
